//
//  YLCCustomMessageViewController.m
//  LinYa
//
//  Created by 初程程 on 2018/3/5.
//  Copyright © 2018年 初程程. All rights reserved.
//

#import "YLCCustomMessageViewController.h"
#import "YLCCustomIconCell.h"
#import "YLCCustomLabelCell.h"
#import "YLCPickModel.h"
#import "YLCEditCustomMessageViewController.h"
#import "ImagePicker.h"
#define CUSTOM_ICON_CELL  @"YLCCustomIconCell"
#define CUSTOM_LABEL_CELL @"YLCCustomLabelCell"
@interface YLCCustomMessageViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIActionSheetDelegate,YLCEditCustomMessageDelegate>

@end

@implementation YLCCustomMessageViewController
{
    UICollectionView *customTable;
    NSArray *cellArr;
    NSArray *titleArr;
    NSArray *keyArr;
    UIImage *headImage;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initDataSource];
    [self createCustomView];
}
- (void)initDataSource{
    titleArr = @[@"头像",@"姓名",@"电话",@"个性签名",@"性别",@"生日"];
    keyArr = @[@"nickName",@"mobile",@"sign",@"sex",@"birthday"];
    cellArr = [_model arrayInfo];
}
- (void)reloadDataWithData:(NSDictionary *)data{
    NSMutableArray *container = [cellArr mutableCopy];
    
    [container setObject:data[@"text"] atIndexedSubscript:[data[@"index"] integerValue]];
    
    cellArr = container.copy;
    
    [customTable reloadData];
}
- (void)createCustomView{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    
    flow.minimumLineSpacing = 0;
    
    customTable = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flow];
    
    customTable.backgroundColor = [UIColor whiteColor];
    
    [customTable registerClass:[YLCCustomIconCell class] forCellWithReuseIdentifier:CUSTOM_ICON_CELL];
    
    [customTable registerClass:[YLCCustomLabelCell class] forCellWithReuseIdentifier:CUSTOM_LABEL_CELL];
    
    customTable.delegate = self;
    
    customTable.dataSource = self;
    
    [self.view addSubview:customTable];
    
    [customTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsZero);
    }];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return cellArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        YLCCustomIconCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CUSTOM_ICON_CELL forIndexPath:indexPath];
        
        cell.title = titleArr[indexPath.row];
        
        cell.headUrl = cellArr[indexPath.row];
        
        if (headImage) {
            cell.headImage = headImage;
        }
        
        return cell;
    }
    YLCCustomLabelCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CUSTOM_LABEL_CELL forIndexPath:indexPath];
    
    cell.title = titleArr[indexPath.row];
    
    cell.custom = cellArr[indexPath.row];
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(self.view.frameWidth, 50);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        [self showImageSheet];
        return;
    }
    
    if (indexPath.row==4) {
        [self showSexPick];
        return;
    }
    if (indexPath.row==5) {
        [self showTimePick];
        return;
    }
    YLCEditCustomMessageViewController *con = [[YLCEditCustomMessageViewController alloc] init];
    
    con.key = keyArr[indexPath.row-1];
    
    con.index = indexPath.row;
    
    con.delegate = self;
    
    [self.navigationController pushViewController:con animated:YES];
}
- (void)editCustomMessageToDict:(NSDictionary *)dict{
    [self reloadDataWithData:dict];
}
- (void)showSexPick{
    YLCPickModel *pickModel = [[YLCPickModel alloc] init];
    pickModel.rowArr = @[@"男",@"女"];
    pickModel.selectIndex = 0;
    RACSubject *signal = [RACSubject subject];
    [YLCHUDShow showPickerListWithList:@[pickModel] signal:signal];
    [signal subscribeNext:^(id x) {
        YLCPickModel *model = x[0];
        [self gotoConfirmSexWithKey:@"sex" message:[NSString stringWithFormat:@"%ld",model.selectIndex+1] value:pickModel.rowArr[model.selectIndex] index:@"4"];
    }];

}
- (void)showTimePick{
    RACSubject *timeSignal = [RACSubject subject];
//    @weakify(self);
    [timeSignal subscribeNext:^(id x) {
//        @strongify(self);
        [self gotoConfirmPostWithKey:@"birthday" message:x index:@"5"];
    }];
    [YLCHUDShow showTimePickWithSignal:timeSignal];
}
- (void)showImageSheet{
    
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相机",@"相册", nil];
    
    [sheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    [[ImagePicker sharedManager] dwSetPresentDelegateVC:self SheetShowInView:self.view InfoDictionaryKeys:buttonIndex];
    
    //回调
    [[ImagePicker sharedManager] dwGetpickerTypeStr:^(NSString *pickerTypeStr) {
        
    } pickerImagePic:^(UIImage *pickerImagePic) {
        headImage = pickerImagePic;
        [self gotoConfirmPostWithKey:@"imgdata" message:[NSString stringWithFormat:@"data:image/jpeg;base64,%@",[headImage base64String]] index:@"0"];
        [customTable reloadData];
    }];    
}
- (void)gotoConfirmSexWithKey:(NSString *)key
                      message:(NSString *)message
                        value:(NSString *)value
                        index:(NSString *)index{
    YLCAccountModel *model = [[YLCAccountManager shareManager] currentAccount];
    
    [YLCNetWorking loadNetServiceWithParam:@{@"token":model.token,@"userId":model.user_id,key:message} method:@"POST" urlPath:@"app/user/updateUser" delegate:self response:^(id responseObject, NSError *error) {
        if (!error) {
            [SVProgressHUD showSuccessWithStatus:@"添加成功"];
            if ([index integerValue]!=0) {
                [self reloadDataWithData:@{@"index":index,@"text":value}];
            }
            
        }else{
            if ([index integerValue]==0) {
                headImage = nil;
                [customTable reloadData];
            }
            
        }
    }];
}
- (void)gotoConfirmPostWithKey:(NSString *)key
                       message:(NSString *)message
                         index:(NSString *)index{
    YLCAccountModel *model = [[YLCAccountManager shareManager] currentAccount];
    
    [YLCNetWorking loadNetServiceWithParam:@{@"token":model.token,@"userId":model.user_id,key:message} method:@"POST" urlPath:@"app/user/updateUser" delegate:self response:^(id responseObject, NSError *error) {
        if (!error) {
            [SVProgressHUD showSuccessWithStatus:@"添加成功"];
            if ([index integerValue]!=0) {
                [self reloadDataWithData:@{@"index":index,@"text":message}];
            }
            
        }else{
            if ([index integerValue]==0) {
                headImage = nil;
                [customTable reloadData];
            }

        }
    }];
}
- (NSString *)title{
    return @"编辑个人资料";
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
